var GKEY = "ABQIAAAALCdLm8DU2gHDctObOm4ddxTM16sdO-7tYrf-Oaslh395x1EaIBT8TqqzX_ue7cOK4Kzz_mEmSCLZYA"; //192

(function() {
  if (window.google && google.gears) {
    return;
  }

  var factory = null;

  if (typeof GearsFactory != 'undefined') {
    factory = new GearsFactory();
  } else {
    try {
      factory = new ActiveXObject('Gears.Factory');
      if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
        factory.privateSetGlobalObject(this);
      }
    } catch (e) {
      if ((typeof navigator.mimeTypes != 'undefined')
           && navigator.mimeTypes["application/x-googlegears"]) {
        factory = document.createElement("object");
        factory.style.display = "none";
        factory.width = 0;
        factory.height = 0;
        factory.type = "application/x-googlegears";
        document.documentElement.appendChild(factory);
      }
    }
  }

  if (!factory) {
    return;
  }

  if (!window.google) {
    google = {};
  }

  if (!google.gears) {
    google.gears = {factory: factory};
  }
})();


var GeoLoc = {
    initialize: function()
    {
        GeoLoc.GEOLOCATION_OPTIONS = {
            enableHighAccuracy: true,
            maximumAge:         600000,
            timeout:            30000   // 30 seconds
        };
        
        if (window.blackberry && blackberry.location && blackberry.location.GPSSupported) {
          GeoLoc._initBlackberryGeolocation();
          return;
        }

        GeoLoc.geo = navigator.geolocation;
        
        
        if (typeof GeoLoc.geo === 'undefined') {
          if (typeof google !== 'undefined' && google.gears && google.gears.factory.create) {
            GeoLoc.geo = google.gears.factory.create('beta.geolocation');
          }
        }

        if (typeof GeoLoc.geo !== 'undefined') {
          GeoLoc.watch = GeoLoc.geo.watchPosition(
            GeoLoc._positionSucceeded,
            GeoLoc._positionFailed,
            GeoLoc.GEOLOCATION_OPTIONS
          );
        } else {
          GeoLoc._initGoogleAjaxAPILoader();
        }
  },

  _initBlackberryGeolocation: function() {
    blackberry.location.onLocationUpdate("GeoLoc.geo._onBlackberryLocationUpdate()");
    blackberry.location.setAidMode(2);
    blackberry.location.refreshLocation();
  },

  _initGoogleAjaxAPILoader: function(callback) {
      this._approximateLocation();
  },

  _approximateLocation: function() {
    var cl = google.loader.ClientLocation;
    if (!cl) return;

    var area = "Around " + cl.address.city + ', ' + cl.address.region;
    var position = {
      coords: {
        latitude:  cl.latitude,
        longitude: cl.longitude
      },
      accuracy:  10000,
      timestamp: new Date(),
      description: area
    };

    Ic.update_position(position);
  },

  _onBlackberryLocationUpdate: function() {
    var l = blackberry.location;
    var position = {
      coords: {
        latitude:  l.latitude,
        longitude: l.longitude
      },
      accuracy:  1000,
      timestamp: new Date()
    };

    Ic.update_position(position);
  },

  _positionSucceeded: function(position) {
    Ic.update_position(position);
  },

  _positionFailed: function(error) {
    var message = "Can't get location";
    switch (error.code) {
    case 0:
      break;
    case 1:
      message += " (permission denied)";
      break;
    case 2:
      message += " (unavailable)";
      break;
    case 3:
      message += " (timeout)";
    }

    Ic.update_position(message);
  }
  
};
window['GeoLoc'] = GeoLoc;

var Ic = {
    initialize: function(){
        this.current_position = false;
        this.addressCache = {};
        this.incidents_near = {};
        this.accesos = Array();
        GeoLoc.initialize();
        
        this.fake_lat = 43.008091;
        this.fake_lon = -2.899146;
        this.fake_position = this.fake_lat+" "+this.fake_lon;
        this.fake_key = this.fake_lat+","+this.fake_lon;
        this.fake_road = "AP-68";
        this.enable_fake = false;
    },
    
    enable: function(tab)
    {
        $("#menu li").removeClass('selected');
        $(tab).addClass('selected');
        try{
            eval("Ic.enable_"+tab.id+"()");
        }
        catch(e){
            $('.container').hide();
            $('#'+tab.id+"_c").show();
        }
    },
    
    loading: function()
    {
        $('.container').hide();
        $('#loading_c').show();
    },
    
    loaded: function(container)
    {
        $('.container').hide();
        $(container).show();
    },
    
    /* Camaras */
    near_cameras: function(where){
        Dajaxice.mobile.get_near_cameras('Ic.near_cameras_callback',{'position':where});
    },
    
    near_cameras_callback: function(data){
        if(data.length == 0){
            alert("No hay camaras cercanas a esta posición");
            return;
        }
        else{
            $('#camaras_cercanas').html("");
            t = $.template('<span class="camera_name">${label} (${distance})</span><img src="${url}" width="100%"/><br/>');
            for (var i=0; i < data.length; i++) {
                $('#camaras_cercanas').append(t,data[i]);
            };
            this.loaded('#camaras_cercanas_container');
        }
    },
    
    /* Puertos */
    enable_puertos: function(){
        Dajaxice.mobile.get_puertos('Ic.enable_puertos_callback');
        this.loading();
    },
    
    enable_puertos_callback: function(data)
    {
        t = $.template('<li onclick="Ic.show_puerto_detail(${l},${i})" class="puerto"><span class="p_label">${label}</span>\
                        <span class="arrow">&raquo;</span><span class="p${estado_articulados} puertos">\
                        </span><span class="p${estado_camiones} puertos"> </span><span class="p${estado_turismos} puertos"> </span><span class="clear"></span></li>');
        $('#puertos_c_ul_primera').html('');
        $('#puertos_c_ul_otros').html('');
        
        this.puertos_afectados = data;
        
        for (var i=0; i < data[0].length; i++) {
            data[0][i]['i'] = i;
            data[0][i]['l'] = 0;
            $('#puertos_c_ul_primera').append(t,data[0][i]);
        }
        
        for (var i=0; i < data[1].length; i++) {
            data[1][i]['i'] = i;
            data[1][i]['l'] = 1;
            $('#puertos_c_ul_otros').append(t,data[1][i]);
        }
        this.loaded('#puertos_c');
    },
    
    show_puerto_detail: function(list, element){
        puerto = this.puertos_afectados[list][element];
        $("#puerto_detalle_turismos").addClass('p'+puerto.estado_turismos);
        $("#puerto_detalle_turismos").addClass('puertos');
        $("#puerto_detalle_articulados").addClass('p'+puerto.estado_articulados);
        $("#puerto_detalle_articulados").addClass('puertos');
        $("#puerto_detalle_camiones").addClass('p'+puerto.estado_camiones);
        $("#puerto_detalle_camiones").addClass('puertos');
        $("#puerto_detalle_label").html(puerto.label);
        $("#puerto_detalle_provincia").html('Provincia: '+puerto.provincia);
        $("#puerto_detalle_carretera").html('Carretera: '+puerto.carretera);
        $("#puerto_detalle_map").html(this.get_static_map(puerto.lat,puerto.lng,470, 180, 14));
        $("#puerto_buscar_camaras").html('<span onclick="Ic.near_cameras(\''+puerto.lat+' '+puerto.lng+'\')">Buscar Camaras</span>');
        this.loaded('#puerto_detalle');
    },
    
    /* Incidencias */
    enable_incidencias: function(){
        Dajaxice.mobile.get_available_roads('Ic.enable_incidencias_callback');
        this.loading();
    },
    
    enable_incidencias_callback: function(data){
        $('#incidencias_c_roads').html('');
        $('#incidencias_c_roads').append('<option value="">Selecciona una carretera</option>');
        for (var i=0; i < data.length; i++) {
            $('#incidencias_c_roads').append('<option value="'+data[i]+'">'+data[i]+'</option>');
        }
        this.loaded('#incidencias_c');
    },
    
    enable_road_incidents: function(){
        road = $('#incidencias_c_roads')[0].value;
        if(road!=""){
            this.loading();
            Dajaxice.mobile.incidents_in_road('Ic.enable_road_incidents_callback',{'road':road});
        }
    },
    
    enable_road_incidents_callback: function(data){
        iconos = {'Accidente':0,'Retención':1,'Desprendimiento':2,
                  'Caída de Objetos':3,'Hielo':4,'Aceite':5,
                  'Avería':6,'Otros':7,'Obras':8,'Alcance':0};
        densidad = {'Flu':0,'Lent':1,'Stop':4,
                    'FLU':0,'LENT':1,'STOP':4};
        t = $.template('<li onclick="Ic.show_incident_detail(${l},${i})" class="c_incidencia"><span class="i${icono} incidencia">\
                        </span> <span class="info_carretera">${carretera} <br/> <span class="in_causa">${causa}\
                        </span></span> <span class="arrow">&raquo;</span><span class="s${densidad} s_right"> </span><span class="clear"></span></li>');
        $('#incidencias_carretera_listado_ul').html('');
        
        this.current_road_incidents = data;
        
        for (var i=0; i < data.length; i++) {
            data[i]['i'] = i;
            data[i]['l'] = 2;
            try{data[i]['icono'] = iconos[data[i].causa];}
            catch(e){data[i]['icono'] = 7;}
            
            try{data[i]['densidad'] = densidad[data[i].afeccion];}
            catch(e){data[i]['densidad'] = 2;}
            
            $('#incidencias_carretera_listado_ul').append(t, data[i]);
        }
        
        this.loaded('#incidencias_carretera_listado_c');
    },
    
    incident_near_me: function(){
        if(!this.current_position){
            alert("Aún no sabemos donde estás, espera un momento.");
            return;
        }
        if(Ic.enable_fake == true){
            carretera = this.fake_road;
            position = this.fake_position;
            key = this.fake_key;
        }
        else{
            position = this.current_position.coords.latitude+" "+this.current_position.coords.longitude;
            carretera = this.road || false;
            key = this.current_position.coords.latitude+","+this.current_position.coords.longitude;
        }
        
        if(this.incidents_near[key]){
            this.current_incidents_near = this.incidents_near[key];
            this.incident_near_me_callback(this.incidents_near[key]);
        }
        else{
            Dajaxice.mobile.incident_near_me('Ic.incident_near_me_callback',{'position':position,'carretera':carretera});
        }
    },
    
    incident_near_me_callback: function(data){
      iconos = {'Accidente':0,'Retención':1,'Desprendimiento':2,
                'Caída de Objetos':3,'Hielo':4,'Aceite':5,
                'Avería':6,'Otros':7,'Obras':8,'Alcance':0};
      densidad = {'Flu':0,'Lent':1,'Stop':4,
                  'FLU':0,'LENT':1,'STOP':4};
                  
        t = $.template('<li onclick="Ic.show_incident_detail(${l},${i})" class="c_incidencia">\
                        <span class="i${icono} incidencia"></span> <span class="info_carretera">${carretera} <br/> <span class="in_causa">${causa}</span>\
                        </span> <span class="arrow">&raquo;</span><span class="s${densidad} s_right"> </span><span class="clear"></span></li>');
        $('#incidencias_near_listado_c_ul').html('');
        $('#incidencias_carretera_listado_c_ul').html('');
        
        if(Ic.enable_fake == true){
            key = Ic.fake_key;
        }
        else{
            key = Ic.current_position.coords.latitude+","+Ic.current_position.coords.longitude;
        }
        
        this.incidents_near[key] = data;
        this.current_incidents_near = data;
        
        for (var i=0; i < data[0].length; i++) {
            data[0][i]['i'] = i;
            data[0][i]['l'] = 0;
            try{data[0][i]['icono'] = iconos[data[0][i].causa];}
            catch(e){data[0][i]['icono'] = 7;}
            
            try{data[0][i]['densidad'] = densidad[data[0][i].afeccion];}
            catch(e){data[0][i]['densidad'] = 2;}
            $('#incidencias_near_listado_c_ul').append(t,data[0][i]);
        }
        
        for (var i=0; i < data[1].length; i++) {
            data[1][i]['i'] = i;
            data[1][i]['l'] = 1;
            try{data[1][i]['icono'] = iconos[data[1][i].causa];}
            catch(e){data[1][i]['icono'] = 7;}
            
            try{data[1][i]['densidad'] = densidad[data[1][i].afeccion];}
            catch(e){data[1][i]['densidad'] = 2;}
            $('#incidencias_carretera_listado_c_ul').append(t,data[1][i]);
        }
        
        this.loaded('#incidencias_near_listado_c');
    },
    
    show_incident_detail: function(list,element){
        iconos = {'Accidente':0,'Retención':1,'Desprendimiento':2,
                'Caída de Objetos':3,'Hielo':4,'Aceite':5,
                'Avería':6,'Otros':7,'Obras':8,'Alcance':0};
        
        densidad = {'Flu':0,'Lent':1,'Stop':4,
                'FLU':0,'LENT':1,'STOP':4};
                                   
        if(list==2){
            incident = this.current_road_incidents[element];
        }
        else{
            incident = this.current_incidents_near[list][element];
        }
        icono = null;
        densi = null;
        try{icono = iconos[incident.causa];}
        catch(e){icono = 7;}
        
        try{densi = densidad[incident.afeccion];}
        catch(e){densi = 2;}
        
        $('#incidencia_detalle_carretera').html(incident.carretera);
        $('#incidencia_detalle_causa').removeClass();
        $('#incidencia_detalle_causa').addClass('i'+icono);
        $('#incidencia_detalle_causa').addClass('incidencia');
        $('#incidencia_detalle_causa').addClass('patch');
        $('#incidencia_detalle_km').html('KM '+incident.km);
        $('#incidencia_detalle_sentido').html('Dirección '+incident.sentido);
        $('#incidencia_detalle_afeccion').addClass('s'+densi);
        $('#incidencia_detalle_afeccion').addClass('s_right');
        $('#incidencia_detalle_distance').html('a '+incident.distance);
        $('#incidencia_detalle_map').html(this.get_static_map(incident.lat,incident.lng,470, 180, 14));
        $("#incidencia_buscar_camaras").html('<span onclick="Ic.near_cameras(\''+incident.lat+' '+incident.lng+'\')">Buscar Camaras</span>');
        this.loaded('#incidencia_detalle');
    },
    
    get_static_map: function(lat,lng,width, height,zoom){
        return '<a href="http://maps.google.com/maps?q='+lat+','+lng+'"><img src="http://maps.google.com/maps/api/staticmap?center='+lat+','+lng+'&zoom='+zoom+'&size='+width+'x'+height+'&maptype=roadmap&mobile=true&markers=color:0xFF4400|'+lat+','+lng+'&key='+GKEY+'&sensor=false" alt="google_map" /></a>';
    },
    
    /*
        Entradas
    */
    show_entry: function(entry){
        if(!this.accesos[entry]){
            this.loading();
            Dajaxice.mobile.city_entries('Ic.show_entry_callback',{'city':entry});
        }
        else{
            this.current_accesos = this.accesos[entry];
            this.show_entry_callback(this.accesos[entry]);
        }
    },
    
    show_entry_callback: function(data)
    {
        t = $.template('<li onclick="Ic.show_entry_detail(${i})"><span class="s${status}"> </span> ${label} <span class="arrow">&raquo;</span></li>');
        $('#accesos_listado_c_ul').html('');
        this.accesos[data[0].city_id] = data;
        this.current_accesos = this.accesos[data[0].city_id];
        for (var i=0; i < data.length; i++) {
            data[i]['i'] = i;
            $('#accesos_listado_c_ul').append(t,data[i]);
        }
        this.loaded('#accesos_listado_c');
    },
    
    show_entry_detail: function(entry)
    {
        t = $.template('<span class="camera_name">${name}</span><img src="${url}" width="100%"/><br/>');
        entry = this.current_accesos[entry];
        $('#accesos_detalle_name').html(entry.label);
        $('#accesos_detalle_estado').removeClass();
        $('#accesos_detalle_estado').addClass("s"+entry.status);
        $('#accesos_detalle_cameras').html('');
        for (var i=0; i < entry.cameras.length; i++) {
            entry.cameras[i];
            d = {'name':entry.cameras[i][0],'url':entry.cameras[i][1]};
            $('#accesos_detalle_cameras').append(t,d);
        };
        
        this.loaded('#accesos_detalle');
    },
    
    /*
     Geo
    */
    set_position: function(address, on_road){
        this.on_road = on_road;
        if(on_road){
            this.road = address;
        }
        else{
            this.road = "";
        }
        $('#user_location').html(address);
    },
    
    update_position_callback: function(response){
        found=false;
        for (var i=0; i < response.Placemark.length; i++)
        {
            try{
                address = response.Placemark[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                if (address.match(/[a-z]+\-\d+/i)){
                    response = response.Placemark[i];
                    found=true;
                    break;
                }
            }
            catch(e){}
        }
        if(Ic.enable_fake == true){
            key = this.fake_key;
            Ic.addressCache[key] = this.fake_road;
            Ic.set_position(this.fake_road,true);
            return;
        }
        if(found){
            key = response.Point.coordinates[1]+","+response.Point.coordinates[0];
            Ic.addressCache[key] = address;
            Ic.set_position(address,true);
        }
        else{
            Ic.set_position("No te encuentras en una carretera",false);
        }
        
    },
    
    update_position: function(position){
        if (this.current_position && this.current_position.coords.accuracy < position.coords.accuracy){
            return;
        }
        
        if(Ic.enable_fake){
            key = this.fake_key;
        }
        else{
            key = position.coords.latitude+","+position.coords.longitude;
        }
        
        address = this.addressCache[key];
        if(!address){
            var script = document.createElement('script');
                script.src = "http://maps.google.com/maps/geo?q="+key+"&key=" +
                GKEY + "&sensor=false&callback=Ic.update_position_callback";
                script.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script);
        }
        else{
            this.set_position(address,false);
        }
        this.current_position = position;
        
        $('#position').html(position.coords.latitude+","+position.coords.longitude);
    }
};
window['Ic'] = Ic;

/*jQuery Templates*/
(function(b){b.template=function(a,c){return new b.template.instance(a,c)};b.template.instance=function(a,c){if(c&&c.regx)c.regx=this.regx[c.regx];this.options=b.extend({compile:false,regx:this.regx.standard},c||{});this.html=a;this.options.compile&&this.compile();this.isTemplate=true};b.template.regx=b.template.instance.prototype.regx={jsp:/\$\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,ext:/\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,jtemplates:/\{\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}\}/g};
b.template.regx.standard=b.template.regx.jsp;b.template.helpers=b.template.instance.prototype.helpers={substr:function(a,c,f){return String(a).substr(c,f)}};b.extend(b.template.instance.prototype,{apply:function(a){if(this.options.compile)return this.compiled(a);else{var c=this,f=this.helpers;return this.html.replace(this.options.regx,function(i,g,e,d){if(e)if(e.substr(0,5)=="this.")return c.call(e.substr(5),a[g],a);else{if(d){i=/^\s*['"](.*)["']\s*$/;d=d.split(",");for(var h=0,k=d.length;h<k;h++)d[h]=
d[h].replace(i,"$1");d=[a[g]].concat(d)}else d=[a[g]];return f[e].apply(f,d)}else return a[g]!==undefined?a[g]:""})}},compile:function(){var a=b.browser.mozilla?"+":",",c=function(i,g,e,d){if(e){d=d?","+d:"";if(e.substr(0,5)!="this.")e="fm."+e+"(";else{e='this.call("'+e.substr(5)+'", ';d=", values"}}else{d="";e="(values['"+g+"'] == undefined ? '' : "}return"'"+a+e+"values['"+g+"']"+d+")"+a+"'"},f;if(b.browser.mozilla)f="this.compiled = function(values){ return '"+this.html.replace(/\\/g,"\\\\").replace(/(\r\n|\n)/g,
"\\n").replace(/'/g,"\\'").replace(this.options.regx,c)+"';};";else{f=["this.compiled = function(values){ return ['"];f.push(this.html.replace(/\\/g,"\\\\").replace(/(\r\n|\n)/g,"\\n").replace(/'/g,"\\'").replace(this.options.regx,c));f.push("'].join('');};");f=f.join("")}eval(f);return this}});var j={domManip:b.fn.domManip,text:b.fn.text,html:b.fn.html};b.fn.domManip=function(a){if(a[0].isTemplate){a[0]=a[0].apply(a[1]);delete a[1]}return j.domManip.apply(this,arguments)};b.fn.html=function(a,c){if(a&&
a.isTemplate)a=a.apply(c);return j.html.apply(this,[a])};b.fn.text=function(a,c){if(a&&a.isTemplate)a=a.apply(c);return j.text.apply(this,[a])}})(jQuery);